package id.co.shuba.spamobile.activities;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.model.MenuInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.task.LoginTask;
import id.co.shuba.spamobile.task.SaveXMLTask;
import id.co.shuba.spamobile.util.Base64;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.widget.MenuAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockFragmentActivity implements
		OnItemClickListener {

	private MenuAdapter adapter;
	private ArrayList<MenuInfo> menuList;

	private GridView gridView;
	
	private LogoutReceiver logoutReceiver;
	private LogoutTask _task;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setUpLogoutReceiver();
	    		
		setContentView(R.layout.activity_main);

		prepareList();
		adapter = new MenuAdapter(this, menuList);

		gridView = (GridView) findViewById(R.id.gridMenu);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(this);	
		
		Object obj = getLastCustomNonConfigurationInstance();
		if (obj != null) {		
			_task = (LogoutTask)obj;
			
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("Logging out...");
			dialog.setCancelable(false);
			_task.setDialog(dialog);
		}
	}	
	
	@Override
	public Object onRetainCustomNonConfigurationInstance() {		
		return _task;
	}
	
	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	protected void onDestroy() {		
		unregisterReceiver(logoutReceiver);
		super.onDestroy();
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		
		if (App.DEBUG) {		
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}

	public void prepareList() {
		menuList = new ArrayList<MenuInfo>();
		MenuInfo info = new MenuInfo();
		info.setName("PIPELINE LIST");
		info.setResource(R.drawable.ic_menu_pipeline);
		menuList.add(info);

		info = new MenuInfo();
		info.setName("PIPELINE KP");
		info.setResource(R.drawable.ic_menu_inbox);
		menuList.add(info);

		info = new MenuInfo();
		info.setName("VISIT M.FUNDING");
		info.setResource(R.drawable.ic_menu_event);
		menuList.add(info);
		
		info = new MenuInfo();
		info.setName("VISIT M.LENDING");
		info.setResource(R.drawable.ic_menu_event);
		menuList.add(info);

		info = new MenuInfo();
		info.setName("DOWNLOAD");
		info.setResource(R.drawable.ic_menu_download);
		menuList.add(info);

		info = new MenuInfo();
		info.setName("UPLOAD");
		info.setResource(R.drawable.ic_menu_upload);
		menuList.add(info);
		
		info = new MenuInfo();
		info.setName("REFFERAL.F");
		info.setResource(R.drawable.ic_menu_event);
		menuList.add(info);
		
		info = new MenuInfo();
		info.setName("REFFERAL.L");
		info.setResource(R.drawable.ic_menu_event);
		menuList.add(info);
		
		info = new MenuInfo();
		info.setName("EXPORT");
		info.setResource(R.drawable.ic_menu_sync);
		menuList.add(info);
		
		/*
		info = new MenuInfo();
		info.setName("IMPORT");
		info.setResource(R.drawable.ic_menu_sync);
		menuList.add(info);*/

		info = new MenuInfo();
		info.setName("LOGOUT");
		info.setResource(R.drawable.ic_menu_logout);
		menuList.add(info);			

		info = new MenuInfo();
		info.setName("EXIT");
		info.setResource(R.drawable.ic_menu_exit);
		menuList.add(info);
		
		/*
		if (App.DEBUG) {
			info = new MenuInfo();
			info.setName("DELETE TRANS");
			info.setResource(R.drawable.ic_action_delete);
			menuList.add(info);
		}*/
	}

	private void save() {
		DatabaseHandler db = new DatabaseHandler(this);
		ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage("Exporting...");

		SaveXMLTask task = new SaveXMLTask(db, dialog, Sessions.getUser(this));

		File sdPat = Environment.getExternalStorageDirectory();
		File spamobilePath = new File(sdPat, "spamobile/export");

		if (!spamobilePath.exists())
			spamobilePath.mkdirs();
		
		UserInfo user = Sessions.getUser(this);
						
		String fileName = String.valueOf(user.getNip() + "-" + App.formatSimpleDate(new Date()) + ".spapkg");
		File file = new File(spamobilePath, fileName);
		if (file.exists())
			file.delete();
		task.execute(file.getPath());

		db.close();
	}
	
	private void offlineDL() {
		/*
		Intent intent = new Intent(this, UpdateOfflineActivity.class);
		intent.putExtra("FILE", App.getOfflineUpdatePath("update.spapkg").getPath());
		startActivity(intent);*/
		
		Intent intent = new Intent(this, ImportListActivity.class);	
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_main, menu);
		MenuItem item = menu.findItem(R.id.menu_settings);
        item.setVisible(App.DEBUG);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Intent intent = new Intent(MainActivity.this, Preference.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		String menuName = adapter.getMenu(arg2).getName();
		if (menuName.equals("PIPELINE LIST")) {

			Intent intent = new Intent(MainActivity.this,
					PipelineListActivity.class);
			startActivity(intent);
		} else if (menuName.equals("PIPELINE KP")) {
			Intent intent = new Intent(MainActivity.this,
					PipelineListActivity.class);
			intent.putExtra("INBOX", true);
			startActivity(intent);
		} else if (menuName.equals("VISIT M.")) {
			Intent intent = new Intent(MainActivity.this,
					MaintenanceVisitListActivity.class);
			startActivity(intent);
		} else if (menuName.equals("DOWNLOAD")) {
			download();
		} else if (menuName.equals("UPLOAD")) {
			upload(false);
		}else if(menuName.equals("REFFERAL.L")){
			Intent intent = new Intent(MainActivity.this,SendReferralLending.class);
			startActivity(intent);
		}else if(menuName.equals("REFFERAL.F")){
			Intent intent = new Intent(MainActivity.this,SendReferralFunding.class);
			startActivity(intent);
		}else if (menuName.equals("ABOUT")) {
			Intent intent = new Intent(MainActivity.this, AboutActivity.class);
			startActivity(intent);
		} else if (menuName.equals("EXPORT")) {
			save();
		} else if (menuName.equals("IMPORT")) {
			offlineDL();
		} else if (menuName.equals("LOGOUT")) {
			//logout();			
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("Logging out...");
			dialog.setCancelable(false);
			new LogoutTask(false, dialog).execute("");
		} else if (menuName.equals("EXIT")) {
			exitApp();
		} else if (menuName.equals("DELETE TRANS")) {
			DatabaseHandler db = new DatabaseHandler(this);
			db.truncateTransactions();
			db.close();
			Toast.makeText(this, "Deleted!",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(MainActivity.this, adapter.getItem(arg2),
					Toast.LENGTH_SHORT).show();
		}
	}
	
	private void logout() {
		Intent intent = new Intent(MainActivity.this, DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.UPLOAD_ALL);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);		
		intent.putExtra(DownloadActivity.PARAMETER_EXIT_WHEN_DONE, true);
		intent.putExtra(DownloadActivity.PARAMETER_GO_TO_LOGIN_WHEN_DONE, true);
		startActivity(intent);
		finish();
	}
	
	class LogoutTask extends AsyncTask<String, Integer, Boolean> {
		private boolean exit;		
		ProgressDialog dialog;
		
		public LogoutTask(boolean exit, ProgressDialog dialog) {
			this.exit = exit;
			this.dialog = dialog;
		}						
		
		public void setDialog(ProgressDialog dialog) {			
			this.dialog = dialog;
			if (getStatus() == Status.RUNNING && !dialog.isShowing())
				dialog.show();
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();			
			if (!dialog.isShowing())
				dialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			WebServiceHelper ws = new WebServiceHelper(MainActivity.this);
			HashMap<String, Object> properties = new HashMap<String, Object>();
			properties.put("aoCode", Sessions.getUser(MainActivity.this).getAoCode());
			try {
				String result = ws.Call("Logout", properties).toString();
				String strJSON = new String(Base64.decode(result, Base64.GZIP)); 									
				
				JSONObject res = new JSONObject(strJSON);
				String error = res.getString("error");
				
				if (!Str.isNullOrEmpty(error) && !"null".equals(error))
					throw new Exception(error);
				
				return true;
			} catch (Exception e) {
				Log.e("Logout", e.getMessage());
				e.printStackTrace();							
				return false;
			}						
		}
	
		@Override
		protected void onPostExecute(Boolean result) {
			Context ctx = null;
			if (dialog != null) {
				ctx  = dialog.getContext();
				
				if (dialog.isShowing())
					dialog.dismiss();
			}
			
			if (dialog != null && dialog.isShowing())
				dialog.dismiss();
			
			if (result) {			
				if (exit) {
					upload(true);            	
	            	MainActivity.this.finish();     
				} else {
					MainActivity.this.logout();
				}
			} else {				
				if (ctx != null) {
					final Context x = ctx;
					new AlertDialog.Builder(new ContextThemeWrapper(ctx,
							R.style.Theme_Sherlock_Light_Dialog))
			        .setIcon(android.R.drawable.ic_dialog_alert)
			        .setTitle(R.string.error)
			        .setMessage("Gagal logout, tidak dapat terhubung ke server")
			        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface d, int which) {
			            	d.dismiss();	            	
			            }
			        })
			        .setNeutralButton("Keluar", new DialogInterface.OnClickListener() {				
						@Override
						public void onClick(DialogInterface d, int which) {
							d.dismiss();
							MainActivity.this.finish();
						}
					})
			        .setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface d, int which) {			            	
			            	d.dismiss();
			            	
			            	ProgressDialog pd = new ProgressDialog(x);
			            	pd.setMessage("Logging out...");
			            	pd.setCancelable(false);
			    			new LogoutTask(exit, dialog).execute("");
			            }
			        })        
			        .show();
				}
			}
		}
	}

	private void download() {
		final CharSequence[] items = new CharSequence[] { "Master", "Prospect" };

		AlertDialog.Builder builder = new AlertDialog.Builder(
				new ContextThemeWrapper(this,
						R.style.Theme_Sherlock_Light_Dialog));
		builder.setTitle("Download");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {				
				if (item == 0) {
					downloadMaster();
				} else {
					Intent intent = new Intent(MainActivity.this,
							DownloadProspectActivity.class);
					startActivity(intent);
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void upload(boolean exit) {
		Intent intent = new Intent(MainActivity.this, DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.UPLOAD_ALL);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);
		if (exit)
			intent.putExtra(DownloadActivity.PARAMETER_EXIT_WHEN_DONE, true);
		
		startActivity(intent);
	}	
	
	private void exitApp() {
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage("Keluar aplikasi?")
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {           
            	dialog.dismiss();            	
            	//upload(true);            	
            	//finish();
            	ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
    			pDialog.setMessage("Logging out...");
    			pDialog.setCancelable(false);

            	new LogoutTask(true, pDialog).execute("");
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();
	}
	
	@Override
	public void onBackPressed() {
		exitApp();       
	}	
	
	private void doDownloadMaster() {
		Intent intent = new Intent(MainActivity.this,
				DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.DOWNLOAD_MASTER);
		//intent.putExtra(DownloadActivity.PARAMETER_DOWNLOAD_UPDATE, true);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);
		startActivity(intent);
	}
	private void downloadMaster() {
		/*
		final CharSequence[] items = new CharSequence[] { "Normal", "Force" };

		AlertDialog.Builder builder = new AlertDialog.Builder(
				new ContextThemeWrapper(this,
						R.style.Theme_Sherlock_Light_Dialog));
		builder.setTitle("Download Method");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {				
				Intent intent = new Intent(MainActivity.this,
						DownloadActivity.class);
				
				intent.putExtra(DownloadActivity.PARAMETER_OPTION,
						DownloadActivity.DOWNLOAD_MASTER);
				//intent.putExtra(DownloadActivity.PARAMETER_DOWNLOAD_UPDATE, true);
				intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);				
				
				if (item == 1) {
					intent.putExtra(DownloadActivity.PARAMETER_FORCE_DOWNLOAD, true);
				}							
				
				startActivity(intent);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
		*/
		
		Intent intent = new Intent(MainActivity.this,
				DownloadActivity.class);
		
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.DOWNLOAD_MASTER);
		//intent.putExtra(DownloadActivity.PARAMETER_DOWNLOAD_UPDATE, true);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);				
		startActivity(intent);
		
		/*
		if (item == 1) {
			intent.putExtra(DownloadActivity.PARAMETER_FORCE_DOWNLOAD, true);
		}*/			
	}	
}
